﻿package framework.core;

//import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.PropertyConfigurator;

import com.hitrust.gs.bean.GSHandleRecord;
import com.hitrust.gs.dao.GSHandleRecordDAO;


/**
 * Creation date: (2003-08-28)
 * @author: adminnistrator
 * 框架总控制器
 */
public class Srv extends javax.servlet.http.HttpServlet
{
    private static boolean sServletInitialed = false;
    private static GSHandleRecordDAO handleRecordDao;
    
    /**
     * 模块是否正常初始化
     * @return true：模块已经初始化；false: 模块未初始化或初始化失败
     */
    public static boolean isInitialed() {
        return sServletInitialed;
    }
    
    /**
	 * Srv 构造子注解。
	 */
	public Srv()
	{
		super();
	}

	public void init() throws ServletException
	{
		String prefix = getServletContext().getRealPath("/");
		PropertyConfigurator.configure(prefix
				+ "/WEB-INF/classes/log4j.properties");
		
		sServletInitialed = true;
		handleRecordDao=new GSHandleRecordDAO();
		LogWriter.init(org.apache.log4j.Logger.getLogger("GW"));
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException
	{
		performTask(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException
	{
		performTask(request, response);
	}

	private void gotoProjectPath(String path, HttpServletRequest req,
			HttpServletResponse res) throws Exception
	{
		String webPath = Config.getWebPath();
		if (path.indexOf(".jsp") != -1 || path.indexOf(".htm") != -1
				|| path.indexOf(".html") != -1)
			//if(path.endsWith(".jsp"))
			//getServletConfig().getServletContext().getRequestDispatcher(
			//		webPath + path).forward(req, res);
			getServletConfig().getServletContext().getRequestDispatcher(
					path).forward(req, res);					
		//getServletConfig().getServletContext().getRequestDispatcher("/v3/Login.jsp").forward(req,res);
		else
			getServletConfig().getServletContext().getRequestDispatcher(path)
					.forward(req, res);
	}

	private void gotoPath(String path, HttpServletRequest req,
			HttpServletResponse res) throws Exception
	{
		getServletConfig().getServletContext().getRequestDispatcher(path)
				.forward(req, res);
	}

	public void performTask(HttpServletRequest req, HttpServletResponse res)
			throws javax.servlet.ServletException, java.io.IOException
	{

		DBConnection con = null;
		SrvContext context = null;
		String action_code = null;
		Action action = null;
		IHandler handler = null;
		String errorPath = "";
		try
		{
			context = new SrvContext(req, res); //得到servlet上下文
			action_code = context.getActionCode(); //得到操作码

			//异常:空的操作代码
			if (null == action_code || action_code.equalsIgnoreCase(""))
			{
				Logger.throwException("Srv.performTask()",
						"没有操作请求代码(action_code),系统无法处理!");
			}
			
			//得到登录上下文
			ILoginContext loginContext = null;
			String loginContextClass = Config.getLoginContextClass();
			if (loginContextClass != null)
			{			
				loginContext = (ILoginContext) Class.forName(loginContextClass)
					.newInstance();
				loginContext = loginContext.init(context);
			}
			boolean isDev = loginContext.isDev();
			if(context.getString("LoginUserRole", "Normal").equalsIgnoreCase("Normal"))
			{
				con = DBConnection.open(isDev);
			} else
				con = DBConnection.open(true);
//			con = DBConnection.open(isDev); //连接数据库

			//操作请求代码检查
			action = ActionManager.getAction(con, action_code);
			if (null == action)
			{
				Logger.throwException("Srv.performTask()", "未知的操作请求代码("
						+ action_code + "),系统无法处理!");
			}
			
			if (loginContextClass != null)
			{
				//登录检查				
				if (action.needLogin() && !loginContext.isLogin())
				{
//					context.setAbsPath(true);
//					//				context.setNextUrl(Config.getLoginUrl());
					if(!action_code.equalsIgnoreCase("login"))
					{
						Map map = context.getParameterMap();
						HashMap paramMap = new HashMap();
						paramMap.putAll(map);
						context.setSessionValue(SrvContext.ParamSessionName, paramMap);
					}
					context.setNextUrl("/system/login.jsp");
					throw new BizException("您没有登录或超时，请重新登录！");
				}
			}

			handler = HandlerManager.getHandler(con, action_code);
			//根据操作代码得到处理类

			//异常:得不到处理类
			if (null == handler)
			{
				Logger.throwException("Srv.performTask()",
						"没有处理类,无法处理操作请求(action_code=" + action_code + ")!");
			}

			con.setAutoCommit(false);

			//处理操作请求
			try
			{
				handler.doAction(con, context, loginContext);
			} catch (Exception e)
			{
				con.rollback();
				throw e;
			}
			con.commit();

			//页面转向
			String nextUrl = context.getNextUrl();
			if (null == nextUrl || nextUrl.equalsIgnoreCase(""))
			{
				return;
			}
			SrvContext.setContext(req, context);
			if (context.isAbsPath())
			{
				gotoPath(nextUrl, req, res);
			} else
			{
				gotoProjectPath(nextUrl, req, res);
				//gotoProjectPath("kkk.jsp",req,res);
			}
		} catch (Exception e)
		{

			try
			{

				
				String sysErrorUrl = Config.getErrorUrl();
				Logger.logException("Srv", e);
				//系统异常
				if (!(e instanceof BizException))
				{
					req.setAttribute("e", e);
					//req.setAttribute("ExceptionId", String.valueOf(exceptionId));
					gotoPath(sysErrorUrl, req, res);
					return;
				}
				String s = sysErrorUrl;
				String error_url = context.getErrorUrl();
				String next_url = context.getNextUrl();
				if (error_url != null && !error_url.equalsIgnoreCase(""))
				{
					s = error_url;
				}
				if (next_url != null && !next_url.equalsIgnoreCase(""))
				{
					s = next_url;
				}
				//BizException,没有提供处理页面,系统处理
				if (s.equalsIgnoreCase(sysErrorUrl))
				{
					req.setAttribute("e", e);
					//req.setAttribute("ExceptionId", String.valueOf(exceptionId));
					gotoPath(sysErrorUrl, req, res);
					return;
				}

				//BizException,程序处理
				context.setErrorMsg(e.getMessage());
				SrvContext.setContext(req, context);
				req.setAttribute("ErrorMsg", e.getMessage());
				gotoProjectPath(s, req, res);
			} catch (Exception e1)
			{
				Logger.logException("Srv.处理异常出错", e1);
			}
		} finally
		{
			//clear resource
			try
			{
				if (con != null && !con.isClosed())
					con.close();
			} catch (Exception e)
			{
				Logger.logException("Srv", e);
			}
		}
	}
}
